<template>
  <el-dialog
    title="项目总成本计划"
    :visible.sync="show"
    width="1700px"
    center
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称" prop="projectName">
            <!-- <el-input v-model="form.projectName" readonly placeholder="自动生成" /> -->
            <el-input
              v-model="form.projectName"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="
                optType === 'add' ? (showTargetSetListModal = true) : null
              "
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input v-model="form.contractAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目计划成本" prop="planCost">
            <el-input v-model="form.planCost" :disabled="disableForm" @blur="calcAllData" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="上交金额" prop="handedAmount">
            <el-input v-model="form.handedAmount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-row />
          <el-row />
        </el-col>
        <el-col :span="8">
          <el-form-item label="上交率" prop="handedRat">
            <el-input v-model="form.handedRat" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div class="tree-table">
        <div style="padding-bottom: 10px;">
          <el-button type="primary" :disabled="disableForm" @click="addRow">新增行</el-button>
          <el-button type="primary" :disabled="disableForm" @click="delRow">删除行</el-button>
          <el-button type="primary" :disabled="disableForm" @click="exportDetail">导出</el-button>
        </div>
        <com-table
          v-model="selectRow"
          highlight-current-row
          default-expand-all
          :cell-style="tableColClassName"
          :data="tableData"
          :columns="columns"
          height="500"
          :total="total"
          row-key="id"
          :tree-props="{ children: 'childrens', hasChildren: 'hasChildren' }"
          @pageChange="pageChange"
        >
          <template v-slot:addNumber="{ row }">
            <template v-if="row.doAdd">
              <el-input v-model="row.addNumber" :disabled="row.doAdd" @input="inputAddNumber" />
            </template>
            <template v-if="!row.doAdd">
              <el-select v-model="row.addNumber" placeholder="新增细目编号" :disabled="row.doAdd" @input="inputAddNumber">
                <el-option label="劳务" value="劳务" />
                <el-option label="材料" value="材料" />
                <el-option label="机械" value="机械" />
              </el-select>
            </template>
          </template>
          <template v-slot:name="{ row }">
            <el-input v-model="row.name" :disabled="row.doAdd" />
          </template>
          <template v-slot:unit="{ row }">
            <el-input v-model="row.unit" :disabled="row.doAdd" />
          </template>
          <template v-slot:contractUnitPrice="{ row }">
            <el-input v-model="row.contractUnitPrice" :disabled="!row.doAdd" />
          </template>
          <template v-slot:contractCount="{ row }">
            <el-input v-model="row.contractCount" :disabled="!row.doAdd" @input="calcSingleData" />
          </template>
          <template v-slot:contractSumPrice="{ row }">
            <el-input v-model="row.contractSumPrice" :disabled="!row.doAdd" />
          </template>
          <template v-slot:costUnitPrice="{ row }">
            <el-input v-model="row.costUnitPrice" @input="calcSingleData" />
          </template>
          <template v-slot:outputTaxRate="{ row }">
            <el-select v-model="row.outputTaxRate" placeholder="销项税税率" @change="calcSingleData">
              <el-option label="3" value="3" />
              <el-option label="9" value="9" />
            </el-select>
          </template>
          <template v-slot:constSumPrice="{ row }">
            <el-input v-model="row.constSumPrice" disabled />
          </template>
          <template v-slot:constructionUnitPrice="{ row }">
            <el-input v-model="row.constructionUnitPrice" :disabled="row.doAdd" @input="calcSingleData" />
          </template>
          <template v-slot:inputTaxRate="{ row }">
            <el-select v-model="row.inputTaxRate" placeholder="进项税税率" @change="calcSingleData">
              <el-option label="0" value="0" />
              <el-option label="1" value="1" />
              <el-option label="3" value="3" />
              <el-option label="6" value="6" />
              <el-option label="9" value="9" />
              <el-option label="13" value="13" />
            </el-select>
          </template>
          <template v-slot:inputTaxAmount="{ row }">
            <el-input v-model="row.inputTaxAmount" />
          </template>
          <template v-slot:constructionTotalPrice="{ row }">
            <el-input v-model="row.constructionTotalPrice" @input="changeConstructionTotalPrice" />
          </template>
          <template v-slot:handedAmount="{ row }">
            <el-input v-model="row.handedAmount" disabled />
          </template>
          <template v-slot:description="{ row }">
            <el-input v-model="row.description" />
          </template>
          <template v-slot:measuredWorkVolume="{ row }">
            <el-input v-model="row.measuredWorkVolume" />
          </template>
          <template v-slot:drawingWorkVolume="{ row }">
            <el-input v-model="row.drawingWorkVolume" />
          </template>
        </com-table>
      </div>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <project-list
      :show-modal.sync="showTargetSetListModal"
      @getSelectedRows="getSelectedRows"
    />
  </el-dialog>
</template>

<script>
import {
  addProjectTotalCostPlanInfo,
  updateProjectTotalCostPlanInfo,
  getProjectTotalCostPlanInfoDetail,
  exportProjectTotalCostPlanInfo
} from '@/api/planManage'
import { workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import ProjectList from '@/components/TreeModal/project'
import moment from 'moment'
export default {
  name: 'AddProjectTotalCostPlanInfo',
  components: {
    fileUploader,
    ProjectList
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      addIndex: -1,
      showFileModal: false,
      selectRow: null,
      targetList: [],
      workflowStatus,
      tableData: [],
      lstDelNodeId: [],
      total: 0,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        projectName: '',
        contractAmount: '',
        planCost: '',
        handedAmount: '',
        handedRat: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: ''
      },
      columns: [
        {
          fixed: 'left',
          label: '原始细目编号',
          prop: 'number',
          width: '150'
        },
        {
          fixed: 'left',
          label: '新增细目编号',
          slot: 'addNumber',
          width: '150'
        },
        {
          fixed: 'left',
          label: '细目名称',
          slot: 'name',
          width: '200'
        },
        {
          label: '清单单位',
          slot: 'unit'
        },
        {
          label: '合同单价',
          slot: 'contractUnitPrice',
          width: '150'
        },
        {
          label: '合同数量',
          slot: 'contractCount',
          width: '150'
        },
        {
          label: '合同合价',
          slot: 'contractSumPrice',
          width: '150'
        },
        {
          label: '图纸工程量',
          slot: 'drawingWorkVolume',
          width: '150'
        },
        {
          label: '目标成本单价',
          slot: 'costUnitPrice',
          width: '150'
        },
        {
          label: '销项税税率(%)',
          slot: 'outputTaxRate',
          width: '150'
        },
        {
          label: '目标成本合价(除税)',
          slot: 'constSumPrice',
          width: '150'
        },
        {
          label: '施工单价(含税)',
          slot: 'constructionUnitPrice',
          width: '150'
        },
        {
          label: '进项税税率(%)',
          slot: 'inputTaxRate',
          width: '150'
        },
        {
          label: '进项税税额',
          slot: 'inputTaxAmount',
          width: '150'
        },
        {
          label: '施工合价(除税)',
          slot: 'constructionTotalPrice',
          width: '150'
        },
        {
          label: '上交金额',
          slot: 'handedAmount',
          width: '150'
        },
        {
          label: '实测工程量',
          slot: 'measuredWorkVolume',
          width: '150'
        },
        {
          label: '描述',
          slot: 'description',
          width: '150'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        projectName: [
          { required: true, message: '项目名称', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      // 每次打开清理数据
      if (val) {
        this.addIndex = -1
        this.targetList = []
        this.total = 0
        this.tableData = []
      }
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach((key) => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  // 初始添加索引
  mounted() {
  },
  methods: {
    // 导出详情
    exportDetail() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 去同步表格数据
          this.toSyncTableData()

          const params = {
            projectTotalCostPlanInfo: {
              ...this.form
            },
            lstAttachment: this.fileList,
            lstProjectTotalCostPlanDetail: this.targetList
          }

          exportProjectTotalCostPlanInfo(params).then((res) => {
            const url = window.URL.createObjectURL(new Blob([res]), {
              type: 'application/vnd.ms-excel'
            })
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', `项目总成本计划${new Date().getTime()}.xls`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
        }
      })
    },
    // 表格列样式名称
    tableColClassName(row) {
      // 只处理施工合价(除税)
      if (row.column.label !== '施工合价(除税)') {
        return
      }
      if (row.row.displayGreenColor) {
        return { background: 'green' }
      } else if (row.row.displayRedColor) {
        return { background: 'red' }
      } else {
        return ''
      }
    },
    // 减量添加索引
    addIndexDec() {
      this.addIndex = this.addIndex - 1
    },
    inputAddNumber() {
      if (this.selectRow) {
        this.selectRow.number = this.selectRow.addNumber
      }
    },
    addRow() {
      if (!this.selectRow) {
        this.$message({ type: 'success', message: '请选择某一个清单!' })
        return
      }

      if (!this.selectRow.doAdd) {
        this.$message({ type: 'success', message: '该清单不能添加!' })
        return
      }

      this.selectRow.childrens.push({
        doAdd: false,
        id: this.addIndex,
        parentId: this.selectRow.id,
        number: '',
        name: '',
        unit: '',
        childrens: [],
        constSumPrice: '',
        costUnitPrice: '',
        handedAmount: '',
        description: '',
        contractCount: '',
        contractUnitPrice: '',
        contractSumPrice: '',
        drawingWorkVolume: '',
        measuredWorkVolume: ''
      })

      this.addIndexDec()

      this.total = this.total + 1
    },
    delRow() {
      if (!this.selectRow) {
        this.$message({ type: 'success', message: '请选择某一个清单!' })
        return
      }

      if (this.selectRow.doAdd) {
        this.$message({ type: 'success', message: '该清单不能删除!' })
        return
      }

      const getCopyNode = (source, target) => {
        source.forEach(item => {
          const element = {
            ...item,
            childrens: []
          }
          getCopyNode(item.childrens, element.childrens)
          if (item.id !== this.selectRow.id) {
            target.push(element)
          }
        })
      }

      // 缓存删除节点Id
      this.lstDelNodeId.push(this.selectRow.id)

      const data = []
      getCopyNode(this.tableData, data)

      this.tableData = data

      this.total = this.total - 1
    },
    dateFormat(data) {
      if (data) {
        return moment(data).format('YYYY-MM-DD')
      } else {
        return ''
      }
    },
    // 获取分页数据
    getTablePageData(number) {
      // 获取起始结束
      const getStartEnd = (number) => {
        return {
          start: (number - 1) * 10 + 1,
          end: number * 10
        }
      }

      // 获取起始结束
      const startEnd = getStartEnd(number)

      // 索引
      let index = 0

      // 获取子节点
      const getSlaveNode = (source, target) => {
        source.forEach(item => {
          // 索引累加
          index += 1
          if (startEnd.start <= index && index <= startEnd.end) {
            const element = {
              ...item,
              childrens: []
            }
            getSlaveNode(item.childrens, element.childrens)
            target.push(element)
          }
        })
      }

      // 获取主节点
      const getMasterNode = (source, target) => {
        source.forEach(item => {
          // 索引累加
          index += 1
          if (startEnd.start <= index && index <= startEnd.end) {
            const element = {
              ...item,
              childrens: []
            }
            getSlaveNode(item.childrens, element.childrens)
            target.push(element)
          } else {
            getMasterNode(item.childrens, target)
          }
        })
      }
      const data = []
      getMasterNode(this.targetList, data)
      this.tableData = data
    },
    // 去同步表格数据
    toSyncTableData() {
      // 目标数据
      const target = this.targetList
      // 原始数据
      const source = []
      const getMapToArray = (data) => {
        data.forEach(item => {
          source.push(item)
          if (item.childrens) {
            getMapToArray(item.childrens)
          }
        })
      }
      getMapToArray(this.tableData)
      // 数据对比
      const compare = (source, target) => {
        const same = (source.parentId === target.parentId && source.number === target.number && source.name === target.name)
        return same
      }
      // 数据更新
      const update = (source, target) => {
        target.doAdd = source.doAdd
        target.operate = source.operate
        target.name = source.name
        target.unit = source.unit
        target.constSumPrice = source.constSumPrice
        target.costUnitPrice = source.costUnitPrice
        target.handedAmount = source.handedAmount
        target.description = source.description
        target.contractCount = source.contractCount
        target.contractUnitPrice = source.contractUnitPrice
        target.contractSumPrice = source.contractSumPrice
        target.outputTaxRate = source.outputTaxRate
        target.constructionUnitPrice = source.constructionUnitPrice
        target.inputTaxRate = source.inputTaxRate
        target.inputTaxAmount = source.inputTaxAmount
        target.constructionTotalPrice = source.constructionTotalPrice
        target.drawingWorkVolume = source.drawingWorkVolume
        target.measuredWorkVolume = source.measuredWorkVolume
      }
      // 寻找新增行
      let find = false
      const findAddRow = (data, id) => {
        data.forEach(item => {
          if (item.id === id) {
            find = true
          }
          if (item.childrens) {
            findAddRow(item.childrens, id)
          }
        })
      }
      // 更新新增行
      const updateAddRow = (source, target) => {
        source.forEach(item => {
          if (item.id === target.id) {
            update(target, item)
          }
          if (item.childrens) {
            updateAddRow(item.childrens, target)
          }
        })
      }
      // 更新源数据到目标数据中
      const updateSourceToTargetData = (source, target) => {
        target.forEach(item => {
          // 如果数据匹配，则更新
          if (compare(source, item)) {
            update(source, item)
            return
          }
          // 如果是新增并且父节点Id等于当前Id，则添加
          if (!source.doAdd && source.parentId === item.id) {
            debugger
            // 已存在，则不添加，否则更新
            find = false
            findAddRow(this.targetList, source.id)
            if (!find) {
              item.childrens.push({ ...source })
            } else {
              updateAddRow(this.targetList, source)
            }
            return
          }
          updateSourceToTargetData(source, item.childrens)
        })
      }
      source.forEach(item => {
        updateSourceToTargetData(item, target)
      })

      // 移除被删除节点
      const node = []
      const removeDelNode = (source, target) => {
        source.forEach(item => {
          const ele = {
            ...item,
            childrens: []
          }
          removeDelNode(item.childrens, ele.childrens)
          if (this.lstDelNodeId.indexOf(ele.id) === -1) {
            target.push(ele)
          }
        })
      }
      removeDelNode(this.targetList, node)
      this.targetList = node
    },
    // 分页切换
    pageChange(page) {
      // 去同步表格数据
      this.toSyncTableData()
      // 获取表格分页数据
      this.getTablePageData(page.pageNum)
    },
    getSelectedRows(obj) {
      // 将值赋给
      this.form = {
        projectName: obj.row.projName
      }
      let count = 0
      const formateData = (data) => {
        return data.map((item) => {
          count = count + 1
          const { number, name, unit, childrens, parentId } = item
          return {
            id: count,
            doAdd: true,
            parentId,
            number,
            name,
            unit,
            ...(childrens
              ? {
                childrens: formateData(childrens)
              }
              : {}),
            constSumPrice: '',
            costUnitPrice: '',
            handedAmount: '',
            description: '',
            outputTaxRate: '',
            constructionUnitPrice: '',
            inputTaxRate: '',
            inputTaxAmount: '',
            constructionTotalPrice: '',
            contractCount: item.contractWorkVolume,
            contractUnitPrice: item.price,
            contractSumPrice: item.amount,
            drawingWorkVolume: item.drawingWorkVolume,
            measuredWorkVolume: item.measuredWorkVolume
          }
        })
      }
      this.targetList = formateData(obj.list)

      this.total = count

      // 获取分页数据
      this.getTablePageData(1)

      this.getContractAmount()
    },
    getDocDetail(id) {
      getProjectTotalCostPlanInfoDetail({
        projectTotalCostPlanInfoId: id
      }).then((res) => {
        const { lstAttachment, lstProjectTotalCostPlanDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstProjectTotalCostPlanDetail && lstProjectTotalCostPlanDetail.length > 0) {
          this.targetList = lstProjectTotalCostPlanDetail

          let count = 0
          const formatData = (data) => {
            data.forEach(item => {
              // 索引累加
              count += 1
              if (item.childrens) {
                formatData(item.childrens)
              }
            })
          }

          formatData(this.targetList)

          this.total = count

          // 获取分页数据
          this.getTablePageData(1)

          // 改变施工合价颜色
          const changeConstructionTotalPriceColor = (data) => {
            data.forEach(item => {
              this.setConstructionTotalPriceAttr(item)
              if (item.childrens) {
                changeConstructionTotalPriceColor(item.childrens)
              }
            })
          }
          changeConstructionTotalPriceColor(this.tableData)
        }
      })
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 去同步表格数据
          this.toSyncTableData()

          // 清除id字段
          const formatData = (data) => {
            data.forEach(item => {
              item.id = null
              if (item.childrens) {
                formatData(item.childrens)
              }
            })
          }

          formatData(this.targetList)

          const params = {
            projectTotalCostPlanInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstProjectTotalCostPlanDetail: this.targetList
          }
          const fn =
            this.optType === 'add'
              ? addProjectTotalCostPlanInfo
              : updateProjectTotalCostPlanInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    // 设置施工合价颜色属性
    setConstructionTotalPriceAttr(row) {
      // 只处理非新增行
      if (!row.doAdd) {
        return
      }
      // 施工合价为空不显示颜色
      if (!row.constructionTotalPrice) {
        return
      }
      // 施工合价大于目标成本合价标红，小于则标绿
      let constructionTotalPrice = 0
      let constSumPrice = 0

      if (row.constructionTotalPrice) {
        constructionTotalPrice = Number.parseFloat(row.constructionTotalPrice)
      }
      if (row.constSumPrice) {
        constSumPrice = Number.parseFloat(row.constSumPrice)
      }

      if (constructionTotalPrice > constSumPrice) {
        row.displayRedColor = true
        row.displayGreenColor = false
      } else {
        row.displayGreenColor = true
        row.displayRedColor = false
      }
    },
    // 施工合价改变时
    changeConstructionTotalPrice() {
      const parentId = this.selectRow.parentId
      let find = null
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          // 找到计算施工合价的父节点
          if (item.id === parentId) {
            find = item
          }
          // 新增节点、父节点相同并且施工合价不为空
          if (!item.doAdd && item.parentId === parentId && item.constructionTotalPrice) {
            sum += Number.parseFloat(item.constructionTotalPrice)
          }
        })
      }
      formateData(this.tableData)

      if (find) {
        find.constructionTotalPrice = sum.toFixed(2)
        this.setConstructionTotalPriceAttr(find)
      }
    },
    // 获取合同金额
    getContractAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.contractSumPrice) {
            sum += Number.parseFloat(item.contractSumPrice)
          }
        })
      }
      formateData(this.targetList)
      this.form.contractAmount = sum.toFixed(2)
      this.$forceUpdate()
    },
    // 获取目标成本合价
    getTargetCostSumPrice() {
      // 目标成本合价 = 目标成本单价 /（销项税税率% / 100 + 1）* 图纸工程量
      let targetCostUnitPrice = 0
      let outputTaxRate = 0
      let drawingWorkVolume = 0

      if (this.selectRow.costUnitPrice) {
        targetCostUnitPrice = this.selectRow.costUnitPrice
      }
      if (this.selectRow.outputTaxRate) {
        outputTaxRate = this.selectRow.outputTaxRate
      }
      if (this.selectRow.drawingWorkVolume) {
        drawingWorkVolume = this.selectRow.drawingWorkVolume
      }

      const constSumPrice = Number.parseFloat(targetCostUnitPrice) / (Number.parseFloat(outputTaxRate) / 100 + 1) * Number.parseFloat(drawingWorkVolume)
      this.selectRow.constSumPrice = constSumPrice.toFixed(2)
      this.setConstructionTotalPriceAttr(this.selectRow)
    },
    // 获取进项税税额
    getInputTaxAmount() {
      // 进项税税额 = 施工单价 /（进项税税率% / 100 + 1）* 进项税税率% / 100 * 图纸工程量
      let constructionUnitPrice = 0
      let inputTaxRate = 0
      let drawingWorkVolume = 0

      if (this.selectRow.constructionUnitPrice) {
        constructionUnitPrice = this.selectRow.constructionUnitPrice
      }
      if (this.selectRow.inputTaxRate) {
        inputTaxRate = this.selectRow.inputTaxRate
      }
      if (this.selectRow.drawingWorkVolume) {
        drawingWorkVolume = this.selectRow.drawingWorkVolume
      }

      const inputTaxAmount = Number.parseFloat(constructionUnitPrice) / (Number.parseFloat(inputTaxRate) / 100 + 1) * Number.parseFloat(inputTaxRate) / 100 * Number.parseFloat(drawingWorkVolume)
      this.selectRow.inputTaxAmount = inputTaxAmount.toFixed(2)
    },
    // 获取施工合价
    getConstructionTotalPrice() {
      // 只处理新增行
      if (this.selectRow.doAdd) {
        return
      }
      // 施工合价 = 图纸工程量 * 施工单价 - 进项税税额
      let drawingWorkVolume = 0
      let constructionUnitPrice = 0
      let inputTaxAmount = 0

      if (this.selectRow.drawingWorkVolume) {
        drawingWorkVolume = this.selectRow.drawingWorkVolume
      }
      if (this.selectRow.constructionUnitPrice) {
        constructionUnitPrice = this.selectRow.constructionUnitPrice
      }
      if (this.selectRow.inputTaxAmount) {
        inputTaxAmount = this.selectRow.inputTaxAmount
      }

      const constructionTotalPrice = Number.parseFloat(drawingWorkVolume) * Number.parseFloat(constructionUnitPrice) - Number.parseFloat(inputTaxAmount)
      this.selectRow.constructionTotalPrice = constructionTotalPrice.toFixed(2)

      this.changeConstructionTotalPrice()
    },
    // 获取上交金额
    getHandedAmount() {
      // 新增行不计算上交金额
      if (!this.selectRow.doAdd) {
        return
      }
      // 上交金额 = 合同合价 - 成本合价
      let contractSumPrice = 0
      let constSumPrice = 0
      if (this.selectRow.contractSumPrice) {
        contractSumPrice = this.selectRow.contractSumPrice
      }
      if (this.selectRow.constSumPrice) {
        constSumPrice = this.selectRow.constSumPrice
      }
      const handedAmount = Number.parseFloat(contractSumPrice) - Number.parseFloat(constSumPrice)
      this.selectRow.handedAmount = handedAmount.toFixed(2)
    },
    // 计算单个数据
    calcSingleData() {
      this.getContractAmount()
      this.getTargetCostSumPrice()
      this.getInputTaxAmount()
      this.getConstructionTotalPrice()
      this.getHandedAmount()
    },
    // 获取多个金额
    getMultiAmount() {
      /**
       * 项目计划成本 = 累计成本合价
       * 上交金额 = 累计上交金额
       * 上交率 = 上交金额 / 合同合价
       */
      // 累计成本合价
      let sumCostSumPrice = 0
      // 累计上交金额
      let sumHandedAmount = 0
      // 累计合同合价
      let sumContractSumPrice = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.constSumPrice && item.doAdd) {
            sumCostSumPrice += Number.parseFloat(item.constSumPrice)
          }
          if (item.handedAmount && item.doAdd) {
            sumHandedAmount += Number.parseFloat(item.handedAmount)
          }
          if (item.contractSumPrice) {
            sumContractSumPrice += Number.parseFloat(item.contractSumPrice)
          }
        })
      }
      formateData(this.targetList)
      this.form.planCost = sumCostSumPrice.toFixed(2)
      this.form.handedAmount = sumHandedAmount.toFixed(2)
      this.form.handedRat = (sumHandedAmount / sumContractSumPrice).toFixed(2)
      this.$forceUpdate()
    },
    // 计算所有数据
    calcAllData() {
      // 去同步表格数据
      this.toSyncTableData()
      // 获取多个金额
      this.getMultiAmount()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title {
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409eff;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
